/**
 * BanBu_SelectPhotosViewController
 * @description 本文件提供从相册选择照片之后进入的照片编辑(添加描述)界面
 * @package
 * @author 		yinlinlin
 * @copyright
 * @version 		1.0
 * @description 本文件提供从相册选择照片之后进入的照片编辑(添加描述)界面
 */

#import "BanBu_SelectPhotosViewController.h"
#import "BanBu_selectPhotoCell.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "AppDataManager.h"
#import "AppCommunicationManager.h"
#import "BanBu_PhotoMoveListViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import <MobileCoreServices/UTCoreTypes.h>
#import "RecordAudio.h"
#import "BanBu_ProgressController.h"
@interface BanBu_SelectPhotosViewController ()

@end

@implementation BanBu_SelectPhotosViewController
@synthesize albumModel = _albumModel;
@synthesize info = _info;
@synthesize file_type = _file_type;
@synthesize video_url = _video_url;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_video_url release];
    _video_url = nil;
    //hujhiuhi
    if(_audioManager)
    {
        [_audioManager release];
        _audioManager = nil;
    }
    
    [_info release];
    _info = nil;
    if (_cameraInfo)
    {
        [_cameraInfo release];
        _cameraInfo = nil;
    }
    else
    {
        [_textinfoArr release];
        _textinfoArr = nil;
        [_soundinfoArr release];
        _soundinfoArr = nil;
        [_soundTimeArr release];
        _soundTimeArr = nil;
        
    }
    [_albumModel release];
    _albumModel = nil;
    [_photosArr release];
    [_album_id release];
    self.updateSuccessCallBack = nil;
    [super dealloc];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    if (_file_type == FILE_ALASSET)
    {
        for (int i = 0; i < _photosArr.count; i ++)
        {
            NSString *fileName =[NSString stringWithFormat:@"PhotoSound-%d.amr",i];
            NSString * audioPath = [AppComManager pathForMsgMedia:fileName];
            //上传之前删除之前的录音文件
            if ([FileManager fileExistsAtPath:audioPath])
            {
                [FileManager removeItemAtPath:audioPath error:nil];
            }
        }
    }
    [super viewWillDisappear:animated];
}

- (void)viewWillAppear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [super viewWillAppear:animated];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = UIColorWithRGB(235, 235, 241, 1.0);
    if (IS_IOS_7)
    {
        IoskeyHeight = 64.0;
    }
    else
        IoskeyHeight = 0.0;
    _textinfoArr = [[NSMutableArray alloc]initWithCapacity:10];
    _soundinfoArr = [[NSMutableArray alloc]initWithCapacity:10];
    _soundTimeArr = [[NSMutableArray alloc]initWithCapacity:10];
    if (_file_type == FILE_ALASSET)
    {
        for (int i = 0; i < self.photosArr.count; i ++)
        {
            [_textinfoArr addObject:@""];
            [_soundinfoArr addObject:@""];
            [_soundTimeArr addObject:@""];
        }
    }
    else
    {
        _cameraInfo = [[NSMutableDictionary alloc]initWithDictionary:_info];
    }
    //tableview headerView
    _headerV = [[[UIView alloc]initWithFrame:CGRectMake(0, 0, __MainScreen_Width, 53 - 26)]autorelease];
    _headerV.backgroundColor = UIColorWithRGB(235, 235, 241, 1.0);
    //相册内容需审核后才能显示
//    UIView * addHeadV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 26)];
//    addHeadV.backgroundColor = [UIColor grayColor];
//    [_headerV addSubview:addHeadV];
//    [addHeadV release];
//    UILabel * label3 = [[UILabel alloc]initWithFrame:CGRectMake(20, 6, 280, 15)];
//    label3.backgroundColor = [UIColor clearColor];
//    label3.font = [UIFont systemFontOfSize:13.0];
//    label3.textColor = [UIColor whiteColor];//UIColorWithRGB(115, 115, 116, 1.0);
//    [_headerV addSubview:label3];
//    //    "album_auditNotice" = "相册内容需审核后才能显示";
//    label3.text = NSLocalizedString(@"album_auditNotice", nil);
//    [label3 release];

    
    UILabel * label1 = [[UILabel alloc]initWithFrame:CGRectMake(20, 30 - 25, 180, 15)];
    [_headerV addSubview:label1];
    label1.backgroundColor = UIColorWithRGB(235, 235, 241, 1.0);
    label1.font = [UIFont systemFontOfSize:13.0];
    label1.textColor = UIColorWithRGB(115, 115, 116, 1.0);
    [label1 release];
    UILabel * label2 = [[UILabel alloc]initWithFrame:CGRectMake(150, 31 - 25, 150, 12)];
    label2.backgroundColor = UIColorWithRGB(235, 235, 241, 1.0);
    label2.text = [NSString stringWithFormat:@"%d",_photosArr.count];
    
    //根据选择上传的是图片or视频显示不同
    if (_file_type == FILE_ALASSET)
    {
        label1.text = [NSString stringWithFormat:@"%@: %d",NSLocalizedString(@"album_selectedPhotos", nil),_photosArr.count];
        //        label2.text = NSLocalizedString(@"album_voice_notice", nil);
        
        label2.text = NSLocalizedString(@"album_voice_notice", nil);
        
    }
    else if (_file_type == FILE_PICKER)
    {
        //录像
        if ([[_cameraInfo objectForKey:UIImagePickerControllerMediaType] isEqualToString:(NSString*)kUTTypeMovie])
        {
            label1.text = [NSString stringWithFormat:@"%@: %d",NSLocalizedString(@"album_selectedVideo", nil),1];
            label2.text = @"";
        }
        else
        {
            label1.text = [NSString stringWithFormat:@"%@: %d",NSLocalizedString(@"album_selectedPhotos", nil),1];
            label2.text = NSLocalizedString(@"album_voice_notice", nil);
        }
    }
    else if (_file_type == FILE_KOOLALBUM)
    {
        label1.text = [NSString stringWithFormat:@"%@: %d",NSLocalizedString(@"album_selectedVideo", nil),1];
        label2.text = @"";
    }
    [label1 sizeToFit];
    label2.textColor = UIColorWithRGB(164, 161, 163, 1.0);
    label2.font = [UIFont systemFontOfSize:11.0];
    label2.textAlignment = kTextAlignmentRight;
    [_headerV addSubview:label2];
    [label2 release];
    
    UIImageView * lineImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 52.5 - 26, __MainScreen_Width, 0.5)];
    lineImg.backgroundColor = UIColorWithRGB(188, 186, 193, 1.0);
    [_headerV addSubview:lineImg];
    [lineImg release];
    //headerView定义完成
    //上传按钮

    UIButton* updateBu = [UIButton  buttonWithType:UIButtonTypeCustom];
    
    //获取按钮title的宽度
    CGFloat btnLen = [NSLocalizedString(@"album_update", nil) sizeWithFont:[UIFont systemFontOfSize:16.0] constrainedToSize:CGSizeMake(80, 24)].width;

    updateBu.frame=CGRectMake(0.0, 0.0, btnLen + 20, 24);
    [updateBu setTitle:NSLocalizedString(@"album_update", 上传) forState:UIControlStateNormal];
    [updateBu addTarget:self action:@selector(startUpdatePhotos) forControlEvents:UIControlEventTouchDown];
    updateBu.titleLabel.font = [UIFont systemFontOfSize:16.0];
    UIBarButtonItem* updateBuItem=[[UIBarButtonItem alloc]initWithCustomView:updateBu];
    self.navigationItem.rightBarButtonItem = updateBuItem;
    [updateBuItem release];
    
    _selectTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, __MainScreen_Width,__MainScreen_Height - 44) style:UITableViewStylePlain];
    _selectTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    _selectTable.backgroundColor = UIColorWithRGB(235, 235, 241, 1.0);
    _selectTable.delegate = self;
    _selectTable.dataSource = self;
    _selectTable.backgroundView = nil;
    _selectTable.separatorColor = [UIColor clearColor];
    _selectTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    _selectTable.tableHeaderView = _headerV;
    [self.view addSubview:_selectTable];
    [_selectTable release];
    
    _album_id = [[NSMutableString alloc]initWithString:_albumModel.album_id];
    //    //监听键盘高度的变换
    
}


/**
 * @函数名称：keyboardWillShow:
 * @函数描述：获取键盘高度变化
 * @输入参数：void
 * @输出参数：void
 * @返回值：void
 * @author：yinlinlin
 */
- (void)keyboardWillShow:(NSNotification *)notification {
    const float movementDuration = 0.3f;
    CGRect keyBoardFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_editingRow inSection:0];
    BanBu_selectPhotoCell * cell = (BanBu_selectPhotoCell *)[_selectTable cellForRowAtIndexPath:indexPath];
    NSLog(@"cell.frame.origin.y:%f",cell.frame.origin.y);
    CGFloat updateY = cell.frame.origin.y;
    if (updateY < __MainScreen_Height - 44 - keyBoardFrame.size.height)
    {
        
    }
    else
    {
        [_selectTable setFrame:CGRectMake(0, 0, __MainScreen_Width, __MainScreen_Height - 44 - keyBoardFrame.size.height)];
        [_selectTable setContentOffset:CGPointMake(0, updateY - 100) animated:NO];
        
        //        [self.view animateView:YES withMovement:keyBoardFrame.size.height-IoskeyHeight];
    }
    [UIView commitAnimations];
}
/**
 * @函数名称：keyboardWillHide:处理键盘隐藏
 * @函数描述：
 * @输入参数：void
 * @输出参数：void
 * @返回值：void
 * @author：yinlinlin
 */
- (void)keyboardWillHide:(NSNotification *)notification {
    const float movementDuration = 0.3f;
    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    [_selectTable setFrame:CGRectMake(0, 0, __MainScreen_Width, __MainScreen_Height - 44)];
    //    [self.view animateView:NO withMovement:IoskeyHeight];
    [UIView commitAnimations];
}


#pragma mark - 上传文件
/**
 * @函数名称：startUpdatePhotos
 * @函数描述：开始上传相册文件，文件类型有3种：ALASSET类型照片，拍摄照片，摄像或本地视频
 * @输入参数：void
 * @输出参数：void
 * @返回值：void
 * @author：yinlinlin
 */
- (void)startUpdatePhotos
{
    NSLog(@"开始上传图片");
    
    [self.view endEditing:YES];
    [self.navigationController popViewControllerAnimated:YES];
    //上传alasset型文件，（本地图片）
    if (_file_type == FILE_ALASSET)
    {
        NSMutableDictionary * photoDict = [[NSMutableDictionary alloc]init];
        NSInteger index = 0;
        for (ALAsset * result in self.photosArr)
        {
            //缩略图:sfile
            CGImageRef  ref1 = [result thumbnail];
            //            NSString *thumbImageEncodeStr = [[NSData dataWithData:UIImageJPEGRepresentation([UIImage imageWithCGImage:ref1], 0.3)] base64EncodedString];
            NSData *thumbImageData = [NSData dataWithData:UIImageJPEGRepresentation([UIImage imageWithCGImage:ref1], 0.3)];
            [photoDict setValue:thumbImageData forKey:@"sfile"];//sfile
            //获取大图（高清图）
            CGImageRef ref = [[result  defaultRepresentation]fullScreenImage];
            UIImage *img =[UIImage imageWithCGImage:ref];
            NSLog(@"转换之前：%f %f",img.size.width,img.size.height);
            CGFloat maxlength = (img.size.width > img.size.height)?img.size.width:img.size.height;
            UIImage * image;
            if (maxlength > 1500)
            {
                image = [MyAppDataManager scaleImage:img proportion:3];
            }
            else if (maxlength > 1000)
            {
                image = [MyAppDataManager scaleImage:img proportion:2];
            }
            else
            {
                image = img;
            }
            NSLog(@"转换之后的长宽:%f %f",image.size.width,image.size.height);
            //根据高清图得到源文件
            //            NSString *fullImageEncodeStr = [[NSData dataWithData:UIImageJPEGRepresentation(image, 0.5)] base64EncodedString];
            NSData *fullImageData = [NSData dataWithData:UIImageJPEGRepresentation(image, 0.7)];
            [photoDict setValue:fullImageData forKey:@"sfull"];
            
            //        //高清图
            //        NSString *highImageEncodeStr = [[NSData dataWithData:UIImageJPEGRepresentation(image, 0.5)] base64EncodedString];
            //        [photoDict setValue:highImageEncodeStr forKey:@"shigh"];
            [photoDict setValue:@"" forKey:@"shigh"];
            
            [photoDict setValue:@"p" forKey:@"kindof"];
            [photoDict setValue:_album_id forKey:@"albumid"];
            [photoDict setValue:[_textinfoArr objectAtIndex:index] forKey:@"stext"];
            [photoDict setValue:[_soundTimeArr objectAtIndex:index] forKeyPath:@"ssoundlen"];
            //存在语音描述
            if ([[_soundinfoArr objectAtIndex:index] isKindOfClass:[NSData class]])
            {
                NSData * soundData = [_soundinfoArr objectAtIndex:index];
                //                [photoDict setValue:[soundData base64EncodedString] forKey:@"ssound"];
                [photoDict setValue:soundData forKey:@"ssound"];
            }
            else
            {
                [photoDict setValue:@"" forKey:@"ssound"];
            }
            //上传队列增加
            BanBu_ProgressController * progressV = [BanBu_ProgressController sharedManager];
            NSDictionary * updateDic = [NSDictionary dictionaryWithObjectsAndKeys:image,@"image",_albumModel.album_title,@"title", nil];
            [progressV addUpdateDate:updateDic];
            [AppComManager updatePhotosToAlbum:photoDict delegate:self];
            
            //            [AppComManager updatePhotosToAlbum:photoDict andReturnDic:^(NSDictionary *dict)
            //             {
            //                 NSLog(@"上传照片返回的数据:%@",dict);
            //                 if (_updateSuccessCallBack)
            //                 {
            //                     _updateSuccessCallBack(dict);
            //                 }
            //             }];
            index ++;
        }
        return;
    }
    else if (_file_type == FILE_PICKER)//(拍照或摄像)
    {
        //摄像
        if ([[_cameraInfo objectForKey:UIImagePickerControllerMediaType] isEqualToString:(NSString*)kUTTypeMovie])
        {
            AVAsset *avAsset      = [AVURLAsset URLAssetWithURL:[_cameraInfo objectForKey:UIImagePickerControllerMediaURL] options:nil];
            NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
            if ([compatiblePresets containsObject:AVAssetExportPresetMediumQuality]) {
                AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
                NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用时间给文件全名，以免重复，在测试的时候其实可以判断文件是否存在若存在，则删除，重新生成文件即可
                [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
                NSString * resultPath = [[NSHomeDirectory() stringByAppendingFormat:@"/Documents/output-%@.mp4", [formater stringFromDate:[NSDate date]]] retain];
                NSLog(@"%@",resultPath);
                [formater release];
                exportSession.outputURL = [NSURL fileURLWithPath:resultPath];
                exportSession.outputFileType = AVFileTypeMPEG4;
                [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
                 {
                     switch (exportSession.status)
                     {
                         case AVAssetExportSessionStatusCompleted:
                         {
                             NSMutableDictionary * photoDict = [[NSMutableDictionary alloc]init];
                             //                             NSMutableDictionary * photoDict = [[NSMutableDictionary alloc]init];
                             //获取压缩的视频数据
                             NSData *data    = [NSData dataWithContentsOfURL:exportSession.outputURL];
                             //删除录制的文件2014年08月25日08:39:33
                             [[NSFileManager defaultManager] removeItemAtPath:resultPath error:nil];
                             //缩略图:sfile
                             NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                             BanBu_selectPhotoCell * cell = (BanBu_selectPhotoCell*)[_selectTable cellForRowAtIndexPath:indexPath];
                             NSData *thumbImageData = [NSData dataWithData:UIImageJPEGRepresentation(cell.photoImgV.image, 0.1)];
                             [photoDict setValue:thumbImageData forKey:@"sfile"];//sfile
                             //根据高清图得到源文件
                             [photoDict setValue:data forKey:@"sfull"];
                             [photoDict setValue:@"" forKey:@"shigh"];
                             
                             [photoDict setValue:@"v" forKey:@"kindof"];
                             [photoDict setValue:_albumModel.album_id forKey:@"albumid"];
                             [photoDict setValue:[_cameraInfo valueForKey:@"text"] forKey:@"stext"];
                             [photoDict setValue:@"" forKey:@"ssound"];
                             //上传队列增加
                             BanBu_ProgressController * progressV = [BanBu_ProgressController sharedManager];
                             NSDictionary * updateDic = [NSDictionary dictionaryWithObjectsAndKeys:cell.photoImgV.image,@"image",_albumModel.album_title,@"title", nil];
                             [progressV addUpdateDate:updateDic];
                             [AppComManager updatePhotosToAlbum:photoDict delegate:self];
                             //                             [AppComManager updatePhotosToAlbum:photoDict andReturnDic:^(NSDictionary *dict)
                             //                              {
                             //                                  NSLog(@"上传视频文件返回的数据:%@",dict);
                             //                                  if (_updateSuccessCallBack)
                             //                                  {
                             //                                      _updateSuccessCallBack(dict);
                             //                                  }
                             //                              }];
                             
                             break;
                         }
                         default:
                             break;
                     }
                     [exportSession release];
                 }];
            }
        }
        //拍照
        else
        {
            NSURL *imageURL = [_cameraInfo valueForKey:UIImagePickerControllerReferenceURL];
            ALAssetsLibrary * lib = [[ALAssetsLibrary alloc]init];
            [lib assetForURL:imageURL resultBlock:^(ALAsset *asset)
             {
                 NSMutableDictionary * photoDict = [[NSMutableDictionary alloc]init];
                 //UIImagePickerControllerEditedImage 只有设allowediting = yes时才能用
                 UIImage * img = [_cameraInfo objectForKey:UIImagePickerControllerOriginalImage];
                 
                 NSLog(@"%f %f",img.size.width,img.size.height);
                 NSLog(@"转换之前：%f %f",img.size.width,img.size.height);
                 CGFloat maxlength = (img.size.width > img.size.height)?img.size.width:img.size.height;
                 UIImage * image;
                 if (maxlength > 1500)
                 {
                     image = [MyAppDataManager scaleImage:img proportion:3];
                 }
                 else if (maxlength > 1000)
                 {
                     image = [MyAppDataManager scaleImage:img proportion:2];
                 }
                 else
                 {
                     image = img;
                 }
                 NSLog(@"转换之后的长宽:%f %f",image.size.width,image.size.height);
                 
                 //缩略图:sfile
                 NSData *thumbImageData = [NSData dataWithData:UIImageJPEGRepresentation([_cameraInfo objectForKey:UIImagePickerControllerEditedImage], 0.1)];
                 [photoDict setValue:thumbImageData forKey:@"sfile"];//sfile
                 //根据高清图得到源文件
                 NSData *fullImageData = [NSData dataWithData:UIImageJPEGRepresentation(image, 0.7)];
                 [photoDict setValue:fullImageData forKey:@"sfull"];
                 [photoDict setValue:@"" forKey:@"shigh"];
                 
                 [photoDict setValue:@"p" forKey:@"kindof"];
                 [photoDict setValue:_albumModel.album_id forKey:@"albumid"];
                 [photoDict setValue:[_cameraInfo valueForKey:@"text"] forKey:@"stext"];
                 //存在语音描述
                 if ([[_cameraInfo valueForKey:@"sound"] isKindOfClass:[NSData class]])
                 {
                     NSData * soundData = [_cameraInfo valueForKey:@"sound"];
                     [photoDict setValue:soundData forKey:@"ssound"];
                     [photoDict setValue:[_cameraInfo objectForKey:@"ssoundlen"] forKeyPath:@"ssoundlen"];
                 }
                 else
                 {
                     [photoDict setValue:@"" forKey:@"ssound"];
                     [photoDict setValue:@"" forKeyPath:@"ssoundlen"];
                 }
                 BanBu_ProgressController * progressV = [BanBu_ProgressController sharedManager];
                 NSDictionary * updateDic = [NSDictionary dictionaryWithObjectsAndKeys:[_cameraInfo objectForKey:UIImagePickerControllerEditedImage],@"image",_albumModel.album_title,@"title", nil];
                 [progressV addUpdateDate:updateDic];
                 [AppComManager updatePhotosToAlbum:photoDict delegate:self];
                 //                 [AppComManager updatePhotosToAlbum:photoDict andReturnDic:^(NSDictionary *dict)
                 //                  {
                 //                      NSLog(@"上传照片返回的数据:%@",dict);
                 //                      if (_updateSuccessCallBack)
                 //                      {
                 //                          _updateSuccessCallBack(dict);
                 //                      }
                 //                  }];
                 
                 
             }
                failureBlock:^(NSError *error)
             {
                 NSLog(@"处理图片失败");
             }];
            [lib release];
        }
        
    }
    else if (_file_type == FILE_KOOLALBUM)
    {
        NSMutableDictionary * photoDict = [[NSMutableDictionary alloc]init];
        //                             NSMutableDictionary * photoDict = [[NSMutableDictionary alloc]init];
        //获取压缩的视频数据
        NSString * videoName = [AppComManager pathForVideoAlbumMedia:[NSString stringWithFormat:@"%@",[_cameraInfo valueForKey:@"videoPath"]]];
        NSData *data    = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@.mp4",videoName]];
        //缩略图:sfile
        NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        BanBu_selectPhotoCell * cell = (BanBu_selectPhotoCell*)[_selectTable cellForRowAtIndexPath:indexPath];
        NSData *thumbImageData = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@.jpg",videoName]];
        [photoDict setValue:thumbImageData forKey:@"sfile"];//sfile
        //根据高清图得到源文件
        //        NSString *videoEncodeStr = [[NSData dataWithData:data] base64EncodedString];
        [photoDict setValue:data forKey:@"sfull"];
        [photoDict setValue:@"" forKey:@"shigh"];
        
        [photoDict setValue:@"v" forKey:@"kindof"];
        [photoDict setValue:_albumModel.album_id forKey:@"albumid"];
        [photoDict setValue:[_cameraInfo valueForKey:@"text"] forKey:@"stext"];
        [photoDict setValue:@"" forKey:@"ssound"];
        //上传队列增加
        BanBu_ProgressController * progressV = [BanBu_ProgressController sharedManager];
        NSDictionary * updateDic = [NSDictionary dictionaryWithObjectsAndKeys:cell.photoImgV.image,@"image",_albumModel.album_title,@"title", nil];
        [progressV addUpdateDate:updateDic];
        [AppComManager updatePhotosToAlbum:photoDict delegate:self];
        //
        //        [AppComManager updatePhotosToAlbum:photoDict andReturnDic:^(NSDictionary *dict)
        //         {
        //             NSLog(@"上传视频文件返回的数据:%@",dict);
        //             if (_updateSuccessCallBack)
        //             {
        //                 _updateSuccessCallBack(dict);
        //             }
        //         }];
    }
}

#pragma mark - 接口返回数据
- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    [TKLoadingView dismissTkFromView:self.navigationController.view animated:NO afterShow:0];
    
    if(error)
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:1];
    }
    else if([AppComManager respondsDic:resDic isFunctionData:BanBu_v2_Post_Albumfile_Byuser])
    {
        NSLog(@"上传照片代理%@",resDic);
        if (_updateSuccessCallBack)
        {
            _updateSuccessCallBack(resDic);
        }
    }
}
#pragma mark - recordView delegate method

#pragma mark - 录音
/**
 * @函数名称：record:
 * @函数描述：长按录音
 * @输入参数：(UILongPressGestureRecognizer *)longPress
 * @输出参数：void
 * @返回值：void
 * @author：yinlinlin
 */
- (void)record:(UILongPressGestureRecognizer *)longPress
{
    [self.view endEditing:YES];
    _currentIndex = longPress.view.tag - 200;
    UIButton *button = (UIButton *)longPress.view;
    self.myVoiceBu = button;
    if(button.selected)
    {
        CGPoint point = [longPress locationInView:_recordView];
        if(longPress.state == UIGestureRecognizerStateEnded)
        {
            button.selected = NO;
            [_recordView touchesEndInView:point];
            _recordView = nil;
        }
        else
            [_recordView touchesMovedInView:point];
        
        return;
    }
    if (longPress.state == UIGestureRecognizerStateBegan)
    {
        button.selected = YES;
        RecordView *recordView = [[RecordView alloc] initWithFrame:CGRectMake(0, 0, 320, __MainScreen_Height)];
        if (IS_IOS_7)
        {
            recordView.frame = CGRectMake(0, 20, 320, __MainScreen_Height);
        }
        _recordView = recordView;
        NSString *fileName =[NSString stringWithFormat:@"PhotoSound-%d.amr",_currentIndex];
        NSString * audioPath = [AppComManager pathForMsgMedia:fileName];
        //如果存在文件，说明是重录，删除之前文件
        if ([FileManager fileExistsAtPath:audioPath])
        {
            [FileManager removeItemAtPath:audioPath error:nil];
        }
        _recordView.audioPath = audioPath;
        recordView.delegate = self;
        [self.navigationController.view addSubview:recordView];
        [recordView release];

    }
}

#pragma mark - 录音结束
/**
 * @函数名称：recordView:recordDidCompleted:recordTime:
 * @函数描述：录音结束，获取录音数据和录音时间长度
 * @输入参数：void
 * @输出参数：void
 * @返回值：void
 * @author：yinlinlin
 */
- (void)recordView:(RecordView *)recordView recordDidCompleted:(NSData *)audioData recordTime:(int)duration
{

    self.myVoiceBu.selected = NO;
    NSLog(@"语音评论时间:%d",duration);
    if([audioData length] < 100)
    {
        return;
    }
    if (_file_type == FILE_ALASSET)
    {
        [_soundinfoArr replaceObjectAtIndex:_currentIndex withObject:audioData];
        
        [_soundTimeArr replaceObjectAtIndex:_currentIndex withObject:[NSString stringWithFormat:@"%d",duration + 1]];
        NSIndexPath * indexPath = [NSIndexPath indexPathForRow:_currentIndex inSection:0];
        BanBu_selectPhotoCell * cell = (BanBu_selectPhotoCell*)[_selectTable cellForRowAtIndexPath:indexPath];
        [cell.playBu setHidden:NO];
        cell.lenLa.text = [NSString stringWithFormat:@"%d''",duration + 1];
        return;
    }
    else
    {
        [_cameraInfo setObject:audioData forKey:@"sound"];
        [_cameraInfo setObject:[NSString stringWithFormat:@"%d",duration] forKey:@"ssoundlen"];
        NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        BanBu_selectPhotoCell * cell = (BanBu_selectPhotoCell*)[_selectTable cellForRowAtIndexPath:indexPath];
        [cell.playBu setHidden:NO];
        cell.lenLa.text = [NSString stringWithFormat:@"%d''",duration];
    }
    [[AVAudioSession sharedInstance] setActive:NO error: nil];
}


#pragma mark - 播放录音
/**
 * @函数名称：playWithRow:andPlay:
 * @函数描述：点击地row行的播放按钮，判断播放或暂停
 * @输入参数：(NSInteger)row：第几行 (BOOL)is_play：播放or暂停
 * @输出参数：void
 * @返回值：void
 * @author：yinlinlin
 */
- (void)playWithRow:(NSInteger)row andPlay:(BOOL)is_play
{
    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:row inSection:0];
    BanBu_selectPhotoCell * cell = (BanBu_selectPhotoCell *)[_selectTable cellForRowAtIndexPath:indexPath];
    if(_audioManager)
    {
        [cell.playBu setSelected:NO];
        [_audioManager stopPlay];
        [_audioManager release];
        _audioManager = nil;
        if (!is_play)
        {
            return;
            NSLog(@"停止播放");
        }
    }
    _audioManager = [[RecordAudio alloc] init];
    _audioManager.delegate = self;
    // 判断 他 有没有
    NSString *fileName =[NSString stringWithFormat:@"PhotoSound-%d.amr",row];
    _audioManager.audioSavePath = [AppComManager pathForMsgMedia:fileName];
    if ([_audioManager startPlay])
    {
        [cell.playBu setSelected:YES];
        _playingRow = row;
        NSLog(@"播放");
    }
}

#pragma mark - RecordAudioDelegate(播放录音代理)
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player
{
    NSLog(@"begin");
}
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer*)player error:(NSError *)error
{
    //解码错误执行的动作
    NSLog(@"%@",error);
}

-(void)recordAudioDidStopAnimation:(BOOL)flag
{
}

- (void)recordAudio:(AVAudioRecorder *)recorder didFinishRecord:(BOOL)finish error:(NSError *)error
{
    NSLog(@"finish");
}
- (void)recordAudioDidFinishPlay:(BOOL)finish error:(NSError *)error
{
    NSLog(@"停止");
    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:_playingRow inSection:0];
    BanBu_selectPhotoCell * cell = (BanBu_selectPhotoCell *) [_selectTable cellForRowAtIndexPath:indexPath];
    [cell.playBu setSelected:NO];
    
}
#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //    if (section == 0)
    //    {
    //        return 1;
    //    }
    if (_file_type == FILE_ALASSET)
    {
        return self.photosArr.count;
    }
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
    //    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
    //    if (indexPath.section == 0)
    //    {
    //        return 40;
    //    }
    //    else
    //    {
    //        return 70;
    //    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = indexPath.row;
    //    NSInteger section = indexPath.section;
    static NSString * cell1 = @"selectPhotoCell1";
    BanBu_selectPhotoCell * cell = [[BanBu_selectPhotoCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cell1];
    if (!cell)
    {
        cell = [[[BanBu_selectPhotoCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cell1]autorelease];
        
    }
    [cell.soundBu removeGestureRecognizer:[cell.soundBu.gestureRecognizers objectAtIndex:0]];
    if (_file_type == FILE_ALASSET)
    {
        if (row == _photosArr.count - 1)
        {
            [cell.lineImg setFrame:CGRectMake(0, 69.5, __MainScreen_Width, 0.5)];
        }
        else
        {
            [cell.lineImg setFrame:CGRectMake(15, 69.5, __MainScreen_Width - 15, 0.5)];
        }
        NSLog(@"%@",[self.photosArr objectAtIndex:row]);
        ALAsset* result = [self.photosArr objectAtIndex:row];
        cell.photoImgV.image =[UIImage imageWithCGImage:[result thumbnail]];
        cell.photoinfo.delegate = self;
        cell.photoinfo.returnKeyType = UIReturnKeyDone;
        cell.photoinfo.tag = 100 + row;
        cell.photoinfo.text = [_textinfoArr objectAtIndex:row];
        cell.soundBu.tag = 200 + row;
        if ([[_soundinfoArr objectAtIndex:row] isKindOfClass:[NSData class]])
        {
            [cell.playBu setHidden:NO];
        }
        else
        {
            [cell.playBu setHidden:YES];
        }
        UILongPressGestureRecognizer * longpress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(record:)];
        [cell.soundBu addGestureRecognizer:longpress];
        [longpress release];
        __block BanBu_SelectPhotosViewController * bself = self;
        //cell点击语音评论按钮的回调
        [cell setPlayBuPressedCallBack:^ (BOOL play){
            NSLog(@"点击语音播放按钮:%d",row);
            [bself playWithRow:row andPlay:play];
            
        }];
        
        return cell;
        
    }
    else
    {
        [cell.lineImg setFrame:CGRectMake(0, 69.5, __MainScreen_Width, 0.5)];
        if (_file_type == FILE_PICKER)
        {
            NSLog(@"%@",_cameraInfo);
            NSString *mediaType = [_cameraInfo objectForKey:UIImagePickerControllerMediaType];
            if([mediaType isEqualToString:@"public.movie"])
            {
                NSURL *videoURL = [_cameraInfo objectForKey:UIImagePickerControllerMediaURL];
                NSLog(@"found a video");
                //获取视频的thumbnail
                AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
                AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
                gen.appliesPreferredTrackTransform = YES;
                CMTime time = CMTimeMakeWithSeconds(0.0, 600);
                NSError *error = nil;
                CMTime actualTime;
                CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
                UIImage *thumb = [[UIImage alloc] initWithCGImage:image];
                CGImageRelease(image);
                cell.photoImgV.image = thumb;
                [cell.soundBu setHidden:YES];
                
                [cell.playBu setHidden:YES];
            }
            else
            {
                cell.photoImgV.image = [_cameraInfo objectForKey:UIImagePickerControllerEditedImage];
                [cell.soundBu setHidden:NO];
                UILongPressGestureRecognizer * longpress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(record:)];
                cell.soundBu.tag = 200 + row;
                [cell.soundBu addGestureRecognizer:longpress];
                [longpress release];
                //cell点击语音评论按钮的回调
                __block BanBu_SelectPhotosViewController * bself = self;
                [cell setPlayBuPressedCallBack:^ (BOOL play){
                    NSLog(@"点击语音播放按钮:%d",row);
                    [bself playWithRow:row andPlay:play];
                    
                }];
                if ([[_cameraInfo valueForKey:@"sound"] isKindOfClass:[NSData class]])
                {
                    [cell.playBu setHidden:NO];
                }
                else
                {
                    [cell.playBu setHidden:YES];
                }
            }
        }
        else
        {
            NSString * videoName = [AppComManager pathForVideoAlbumMedia:[NSString stringWithFormat:@"%@",[_cameraInfo valueForKey:@"videoPath"]]];
            cell.photoImgV.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@.jpg",videoName]];
            [cell.soundBu setHidden:YES];
            
            [cell.playBu setHidden:YES];
        }
        cell.photoinfo.delegate = self;
        cell.photoinfo.returnKeyType = UIReturnKeyDone;
        cell.photoinfo.tag = 100 + row;
        cell.photoinfo.text = [_cameraInfo valueForKey:@"text"];
        return cell;
    }
}

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (range.location >= 50)
    {
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"noticeNotice", nil) message:NSLocalizedString(@"textLimite", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"confirmNotice", 确定), nil];
        [alert show];
        return NO;
    }
    return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    _editingRow = textField.tag - 100;
    NSLog(@"开始输入");
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (_file_type == FILE_ALASSET)
    {
        NSLog(@"第%d个textfield结束输入：%@", textField.tag - 100,textField.text);
        [_textinfoArr replaceObjectAtIndex:textField.tag - 100 withObject:textField.text];
        return;
    }
    if (_file_type == FILE_PICKER)
    {
        [_cameraInfo setValue:textField.text forKey:@"text"];
    }
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
